// Pages/user/editAddress/editAddress.js
// var qqmapsdk;
var wxwidth = wx.getSystemInfoSync().windowWidth;
var app = getApp();
var page_size = 20;
var page_index = 1; //默认页码
var ch_latitude= ''; //当前
var  ch_longitude= ''; //当前
Page({
  /**
   * 页面的初始数据
   */
  data: {
    ak_code: '3VPBZ-KJ5LQ-7Y55U-GZ6HH-BJ2XH-RBB6B',
    heighthh: 220, //地高度
    con_signee: '', //联系人
    mo_bile: '', //手机号码
    add_ress: '', //详细地址
    is_default: false, //默认不是默认地址
    addressMenuIsShow: false,
    value_sel: [0, 0, 0], //对应数组下标
    province_s: [],
    city_s: [],
    area_s: [],
    areaInfo_name: [], //选中地区名称
    area_id_Info: [], //选中的地区id信息
    address_id: '', //单个地址id
    timeone: 1,
    pageView: false, //这里开始地址选择
    markers: [],
    Type: '', //编辑进入、添加地址进入
    valueName: [],//设置回显选择的地址(name)
    address_list: '', //获取到的地址列表
    curr_id: '', //当前地址Id
    hasMore: false, //数据是否加载完成
    loading: false, //
    searchshow: false,
    searchList: [], //获取到的地址列表
    numberPlate: '',
    house_type: 1,
    isSubimit: false, //避免重复提交
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 初始化动画变量
    var that = this;
    var address_id = options.address_id;
    var Type = options.type;
    console.log(Type);
    that.setData({
      address_id: address_id,
      Type: Type
    })
    // var animation = wx.createAnimation({
    //   duration: 500,
    //   transformOrigin: "50% 50%",
    //   timingFunction: 'ease',
    // })
    // that.animation = animation;
   // that.getProvince(); //获取省份信息      

    if (Type == 1) {
      var lat = wx.getStorageSync('lat');
      var lng = wx.getStorageSync('lng');
      if (lat != '' && lng != '') {
        that.getCityLocation(lat, lng);
      } else {
        wx.getLocation({
          type: 'gcj02',
          success: function(res) {
            wx.setStorageSync('lat', res.latitude);
            wx.setStorageSync('lng', res.longitude);
            that.getCityLocation(res.latitude, res.longitude);
          },
          fail: function(res) {
            app.showToast('拒绝获取位置信息将无法查看当前地址信息', "none", 2000, function() {});
          }
        })
      }

    } else if (Type == 2) {
      that.addressDisplay(address_id);
    }

    // wx.chooseLocation({
    //   success: function (res) {
    //     console.log('结果',res)
    //   }
    //   })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let that = this;
    that.headid = this.selectComponent("#addre_id"); //引入地址    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  //根据经纬度获取城市信息
  getCityLocation: function(latitude, longitude) {
    var that = this;
    console.log('地址', latitude, longitude);
    app.ajax({
      // url: 'https://api.map.baidu.com/geocoder/v2/?ak=' + that.data.ak_code + '&location=' + latitude + ',' + longitude + '&output=json',
      url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=' + that.data.ak_code + '&get_poi=1',
      method: 'GET',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        // success  
        //百度地图返回参数
        // that.getCityCode(res.data.result.addressComponent.province, res.data.result.addressComponent.city, res.data.result.addressComponent.district)
        //腾讯地图返回参数
        console.log('地址', res.data);
        that.getCityCode(res.data.result.address_component.province, res.data.result.address_component.city, res.data.result.address_component.district)
        // 更新用户地址
        // that.updateAddress(res.data.result.addressComponent);
      },
      fail: function() {},

    })
  },
  //根据地址查询地区code
  getCityCode: function(province, city, district) {
    var that = this;
    app.ajax({
      url: 'Common/Areas/getAreasCode',
      method: "POST",
      data: {
        province: province,
        city: city,
        area: district
      },
      success: function(res) {
        //console.log(res.data)
        if (res.data.code == 1000) {
          var areaInfo_name = []; //区域名称
          areaInfo_name.push(res.data.data.province_info.area_name);
          areaInfo_name.push(res.data.data.city_info.area_name);
          areaInfo_name.push(res.data.data.area_info.area_name);
          var area_id_Info = []; //区域id
          area_id_Info.push(res.data.data.province_info.id);
          area_id_Info.push(res.data.data.city_info.id);
          area_id_Info.push(res.data.data.area_info.id);
          that.setData({
            areaInfo_name: areaInfo_name,
            area_id_Info: area_id_Info,
          });

          that.setProDefault(res.data.data);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //根据地址设置更换地址省的默认值
  setProDefault: function(info) {
    console.log('进来了', info);
    var that = this;
    var province_s = that.data.province_s;
    for (var i in province_s) {
      if (province_s[i].id == info.province_info.id) {
        var a = 'value_sel[0]';
        that.setData({
          [a]: parseInt(i)
        })
        app.ajax({
          url: 'Common/Areas/areas',
          method: "POST",
          data: {
            parent_id: province_s[i].id
          },
          success: function(res) {
            if (res.data.code == 1000) {
              // console.log(res.data.data);          
              that.setData({
                city_s: res.data.data
              });
              that.setCityDefault(info);
            } else {
              app.showToast(res.data.message);
            }
          }
        })
      }
    }

  },
  //根据地址设置更换地址市的默认值
  setCityDefault: function(info) {
    var that = this;
    var city_s = that.data.city_s;
    for (var i in city_s) {
      if (city_s[i].id == info.city_info.id) {
        var a = 'value_sel[1]';
        that.setData({
          [a]: parseInt(i)
        })
        app.ajax({
          url: 'Common/Areas/areas',
          method: "POST",
          data: {
            parent_id: city_s[i].id
          },
          success: function(res) {
            if (res.data.code == 1000) {
              // console.log(res.data.data);          
              that.setData({
                area_s: res.data.data
              });
              that.setAreaDefault(info);
            } else {
              app.showToast(res.data.message);
            }
          }
        })
        break;
      }
    }
  },
  //根据地址设置更换地址区的默认值
  setAreaDefault: function(info) {
    var that = this;
    var area_s = that.data.area_s;
    for (var i in area_s) {
      if (area_s[i].id == info.area_info.id) {
        var a = 'value_sel[2]';
        that.setData({
          [a]: parseInt(i)
        })
        break;
      }
    }
  },
  //获取单个用户信息
  addressDisplay(address_id) {
    var that = this;
    app.ajax({
      url: 'User/Useraddress/addressDisplay',
      method: "POST",
      data: {
        address_id: address_id
      },
      success: function(res) {
        if (res.data.code == 1000) {
          var newArrname = [res.data.data.provice, res.data.data.city, res.data.data.area];
          console.log('区域', newArrname)
          var newArrid = [res.data.data.provice_code, res.data.data.city_code, res.data.data.area_code];
          that.setData({
            con_signee: res.data.data.contact,
            mo_bile: res.data.data.contact_tel,
            areaInfo_name: newArrname,
            valueName: newArrname,
            area_id_Info: newArrid,
            add_ress: res.data.data.address,
            is_default: res.data.data.is_default == 1 ? false : true,
            house_type: res.data.data.house_type,
            numberPlate: res.data.data.numberPlate ? res.data.data.numberPlate : '',
          })
          ch_latitude= res.data.data.lat;
          ch_longitude= res.data.data.lng;
          var infoes = { province_info: { id: newArrid[0] }, city_info: { id: newArrid[1] }, area_info: { id: newArrid[2] }};
          that.setProDefault(infoes);

        }
      }
    })
  },
  //联系人输入
  signeeInput: function(e) {
    var that = this;
    var con_signee = e.detail.value;
    that.setData({
      con_signee: con_signee
    })
  },
  //手机号码输入
  bileInput: function(e) {
    var that = this;
    var mo_bile = e.detail.value;
    that.setData({
      mo_bile: mo_bile
    })
  },
  // 输入门牌号
  plateInput(e) {
    var that = this;
    var numberPlate = e.detail.value;
    that.setData({
      numberPlate: numberPlate
    })
  },
  //打开地图选择
  openAddress() {
    var that = this;
    this.headid.startAddressAnimation(true);
  },
  // 一下为地址(地图)选择.........................................................................................
  openaddshoose() {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log('地址选择结果', res);
        ch_longitude = res.longitude;
        ch_latitude = res.latitude;
        that.setData({
          add_ress: res.name
        })
      }
    });
  },
  getSure(data) {
    console.log('确定事件获取地址', data);
    var that = this;
    that.setData({
      areaInfo_name: data.detail.areaName,
      area_id_Info: data.detail.areaId,
      valueName: data.detail.areaName
    })
  },
  //判断是修改还是 新增
  joinEdit(e) {
    var that = this;
    var get_e = e;
//    app.saveFormId(e.detail.formId);
    var address_id = that.data.address_id;
    if (address_id == '') {
      that.add_address(get_e);
    } else {
      that.edit_address(get_e, address_id);
    }
    that.getAddressInfo();
  },
  //查询地址信息,当只有一个地址时为当前地址
  getAddressInfo: function() {
    var that = this;
    var user_id = that.data.user_id;
    app.ajax({
      url: 'User/Useraddress/addressList',
      method: "POST",
      data: {
        page: 1,
        pageSize: 100
      },
      success: function(res) {
        //console.log(res)
        if (res.data.code == 1000) {
          var address = res.data.data[0];
          var address_len = res.data.data.length;
          var address_id = res.data.data[0].address_id;
          if (address_len == 1) {
            wx.setStorageSync("address_id", address_id);
          }
        } else {
          // app.showToast(res.data.message);
        }
      }
    })
  },
  //点击保存
  add_address(e) {
    var that = this;
    var consignee = e.detail.value.consignee;
    var mobile = e.detail.value.mobile;
    var province = e.detail.value.province;
    var city = e.detail.value.city;
    var district = e.detail.value.district;
    var address = e.detail.value.address + '/' + e.detail.value.numberPlate;
    var is_default = e.detail.value.is_default == true ? 2 : 1; // 是否需要设置成默认地址
    var addr_city = e.detail.value.input;
    var areaInfo_name = that.data.areaInfo_name;
    var area_id_Info = that.data.area_id_Info;
    var numreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/; //手机号码正则    
    if (consignee == '') {
      app.showToast('姓名不能为空', "none", 2000, function() {});
      return false;
    }
    if (mobile == '') {
      app.showToast('手机号码不能为空', "none", 2000, function() {});
      return false;
    }
    if (numreg.test(mobile) == false) {
      app.showToast('请输入正确的手机号码', "none", 2000, function() {});
      return false;
    }

    if (areaInfo_name.length == 0) {
      app.showToast('请选择省市区信息', "none", 2000, function() {});
      return false;
    }
    if (ch_latitude == '' || ch_longitude == '') {
      app.showToast('请选择地址', "none", 2000, function() {});
      return false;
    }
    if (address == '' || addr_city == "/") {
      app.showToast('详细地址信息不能为空', "none", 2000, function() {});
      return false;
    }
    app.ajax({
      url: "User/Useraddress/addAddress",
      data: {
        provice: areaInfo_name[0],
        city: areaInfo_name[1],
        area: areaInfo_name[2],
        provice_code: area_id_Info[0],
        city_code: area_id_Info[1],
        area_code: area_id_Info[2],
        address: address,
        contact: consignee,
        contact_tel: mobile,
        is_default: is_default,
        lat: ch_latitude,
        lng: ch_longitude,
        house_type: that.data.house_type
      },
      success: function(res) {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "none", 4000, function() {});
          wx.navigateBack({
            delta: 1
          })
        } else {
          app.showToast(res.data.message, "none", 2000, function() {});
        }
      }
    })

  },

  //点击保存
  edit_address(e, address_id) {
    var that = this;
    var consignee = e.detail.value.consignee;
    var mobile = e.detail.value.mobile;
    var province = e.detail.value.province;
    var city = e.detail.value.city;
    var district = e.detail.value.district;
    var address = e.detail.value.address + '/' + e.detail.value.numberPlate;
    // var is_default = e.detail.value.is_default==true?2:1; // 是否需要设置成默认地址
    var is_default = that.data.is_default == true ? 2 : 1;
    var addr_city = e.detail.value.input;
    var areaInfo_name = that.data.areaInfo_name;
    var area_id_Info = that.data.area_id_Info;
    var numreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/; //手机号码正则  

    if (consignee == '') {
      app.showToast('姓名不能为空', "none", 2000, function() {});
      return false;
    }
    if (mobile == '') {
      app.showToast('手机号码不能为空', "none", 2000, function() {});
      return false;
    }
    if (numreg.test(mobile) == false) {
      app.showToast('请输入正确的手机号码', "none", 2000, function() {});
      return false;
    }
    if (address == false) {
      app.showToast('详细地址信息不能为空', "none", 2000, function() {});
      return false;
    }
    if (areaInfo_name.length == 0) {
      app.showToast('请选择省市区信息', "none", 2000, function() {});
      return false;
    }
    app.ajax({
      url: "User/Useraddress/editAddress",
      data: {
        address_id: address_id,
        provice: areaInfo_name[0],
        city: areaInfo_name[1],
        area: areaInfo_name[2],
        provice_code: area_id_Info[0],
        city_code: area_id_Info[1],
        area_code: area_id_Info[2],
        address: address,
        contact: consignee,
        contact_tel: mobile,
        is_default: is_default,
        lat: ch_latitude,
        lng: ch_longitude,
        house_type: that.data.house_type
      },
      success: function(res) {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "none", 4000, function() {});
          wx.navigateBack({
            delta: 1
          })
        } else {
          app.showToast(res.data.message, "none", 2000, function() {});
        }
      }
    })

  },

  // 选择房屋性质
  radioChange(e) {
    this.setData({
      house_type: e.detail.value
    })
  }
})